import re

from django.contrib.auth.backends import ModelBackend

from .models import User


def jwt_response_payload_handler(token,user=None,request=None):

    return {
        'token':token,
        'user_id':user.id,
        'username': user.username

    }

# 手机号以及账号都可以实现登录
def get_user_by_count(account):
    try:
        if re.match('^1[3-9]\d{9}$',account):
            # 账号是手机号
            user = User.objects.get(mobile = account)
        else:
            user = User.objects.get(username=account)
    except User.DoseNotExist:
        return None

    else:
        return user

class UsernameMobileAuthBackend(ModelBackend):
    """
    自定义用户名或手机号认证
    """
    def authenticate(self, request, username=None, password=None, **kwargs):
        user = get_user_by_count(username)
        if user is not None and user.check_password(password):
            return user






